﻿using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using MugenInjection.Interface;
using MugenInjection.Interface.Components;
using MugenInjection.Scope;
using MugenInjection.Wcf.Scope;
using MugenInjection.Web;
using MugenInjection.Web.Interface;
using MugenInjection.Web.Settings;

namespace MugenInjection.Wcf.Config
{
    /// <summary>
    /// Providing integration with WCF. Added support for ContextRequestScope.
    /// </summary>
    public class MugenWcfApplicationConfiguration : IConfiguration
    {
        #region Implementation of IConfiguration

        /// <summary>
        /// Loads the current configuration.
        /// </summary>
        /// <param name="configuration">The specified <see cref="IApplicationConfiguration"/>.</param>
        public void Load(IApplicationConfiguration configuration)
        {
            var contextRequestProvider = new ContextRequestScopeProvider();
            var injector = configuration.Injector;
            var behaviorManagerComponent = injector.Components.Get<IBehaviorManagerComponent>();
            behaviorManagerComponent.Add<IDispatchMessageInspector>(contextRequestProvider);

            injector.BindWithManualBuild<IInstanceProvider>()
                .To<MugenInjectionInstanceProvider>()
                .NamedBinding(WcfConfigExtension.InstanceProviderKey)
                .Build();
            injector.BindWithManualBuild<IScopeProvider>()
                .ToConstant(contextRequestProvider)
                .NamedBinding(WebContextScopeLifecycle.OperationRequestScopeProvider)
                .Build();
        }

        /// <summary>
        /// Unloads the current configuration.
        /// </summary>
        /// <param name="configuration">The specified <see cref="IApplicationConfiguration"/>.</param>
        public void Unload(IApplicationConfiguration configuration)
        {
            var injector = configuration.Injector;
            injector.Components.Get<IBehaviorManagerComponent>().Remove<IDispatchMessageInspector>();
            injector.Unbind<IInstanceProvider>(WcfConfigExtension.InstanceProviderKey);
            injector.Unbind<IScopeProvider>(WebContextScopeLifecycle.OperationRequestScopeProvider);
        }

        #endregion
    }
}